package fu.capstone.hanoicityguide.common.utility;

import java.io.File;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.webkit.URLUtil;

public class DownloadMapFiles extends AsyncTask<String, Void, Void> {

	private AlertDialog.Builder alertDialogBuilder;
	private Context context;

	public DownloadMapFiles(Context ctx) {
		this.context = ctx;
		alertDialogBuilder = new AlertDialog.Builder(ctx);
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		alertDialogBuilder.setTitle("Thanks for purchasing");
		alertDialogBuilder
				.setMessage("Your download has been started, please wait ...");
		alertDialogBuilder.setCancelable(false);
		alertDialogBuilder.setPositiveButton("OK", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}

	@Override
	protected Void doInBackground(String... params) {
		// TODO Auto-generated method stub

		new File(Environment.getExternalStorageDirectory(),
				"vietnam-latest.osm-gh").mkdir();

		DownloadManager mgr = (DownloadManager) context
				.getSystemService(Context.DOWNLOAD_SERVICE);

		for (int i = 0; i < params.length; i++) {
			Uri source = Uri.parse(params[i]);
			// Uri destination = Uri.fromFile(new File(local file path));

			DownloadManager.Request request = new DownloadManager.Request(
					source);
			request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
					| DownloadManager.Request.NETWORK_MOBILE);
			request.setVisibleInDownloadsUi(true);
			request.setDestinationUri(Uri.fromFile(new File(Environment
					.getExternalStorageDirectory() + "/vietnam-latest.osm-gh",
					URLUtil.guessFileName(params[i], null, null))));
			// request.setNotificationVisibility(DownloadManager
			// .Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);+
			// "vietnam-latest.osm-gh"
			request.allowScanningByMediaScanner();

			mgr.enqueue(request);
		}
		return null;
	}

}
